package com.domainchen.framework.core.proxy;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import net.sf.cglib.proxy.MethodProxy;

/**
 * @author domainchen or cytxiamen@163.com
 * @version 创建时间：2016年3月11日 下午5:17:41
 * @类说明 代理链
 */
public class ProxyChain {

	private final Class<?> targetClass;// 目标类
	private final Object targetObject;// 目标对象
	private final Method targetMethod;// 目标方法
	private final MethodProxy methodProxy;// 方法代理-CGLib提供的方法对象,在doProxyChain方法内被调用
	private final Object[] methodParams;// 方法参数

	// 代理列表
	private List<Proxy> proxyList = new ArrayList<Proxy>();

	private int proxyInt = 0;

	public ProxyChain(Class<?> targetClass, Object targetObject, Method targetMethod, MethodProxy methodProxy,
			Object[] methodParams, List<Proxy> proxyList) {
		super();
		this.targetClass = targetClass;
		this.targetObject = targetObject;
		this.targetMethod = targetMethod;
		this.methodProxy = methodProxy;
		this.methodParams = methodParams;
		this.proxyList = proxyList;
	}

	public Class<?> getTargetClass() {
		return targetClass;
	}

	public Method getTargetMethod() {
		return targetMethod;
	}

	public Object[] getMethodParams() {
		return methodParams;
	}

	public Object doProxyChain() throws Throwable {
		Object methodResult = null;
		if (proxyInt < proxyList.size()) {
			methodResult = proxyList.get(proxyInt++).doProxy(this);
		} else {
			methodResult = methodProxy.invokeSuper(targetObject, methodParams);
		}
		return methodResult;
	}
}
